/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Apr 14, 2012  3:41:08 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.fi.inbound
 * File Name : PaymentRequestOutgoingService.java
 * TODO
 */
package sap.business.fi.inbound;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import jpa.entitys.synchro.common.ACTION_HANDLER;
import jpa.entitys.synchro.staging.FiLivOutgoingpaymentInb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.FiLivOutgoingpaymentInbServices;

import org.apache.log4j.Logger;

import com.sap.mw.jco.JCO;

import promis.utility.CommonService;
import sap.business.commons.services.CommonJCOReturn;
import apps.promis.in.construction.PaymentRequestOutgoingAction;

/**
 * @author chatree
 *
 */
public class PaymentRequestOutgoingService {
	private static final Logger log = Logger.getLogger(PaymentRequestOutgoingService.class);

	public void CreatedSync(JCO.ParameterList input, JCO.ParameterList tables, JCO.ParameterList output, String structureOrTableName) {
		List<FiLivOutgoingpaymentInb> lst_object = new ArrayList<FiLivOutgoingpaymentInb>();
		List<FiLivOutgoingpaymentInb> lst = null;
		JCO.Table table = tables.getTable(structureOrTableName);
		int records = -1;
		try{
			
			EntityManager em = new SessionEntityManager().CreatedEntityManager();
			FiLivOutgoingpaymentInbServices FiLivOutgoingpaymentInbServ = new FiLivOutgoingpaymentInbServices(em);
			String instance_no = FiLivOutgoingpaymentInbServ.GetNewInstanceNo();
			
			records = table.getNumRows();
			for(int i = 0; i < records; i++)
			{
				System.out.println("i ="+ i);
				table.setRow(i);			
				FiLivOutgoingpaymentInb model = new FiLivOutgoingpaymentInb();
				
				model.setInstanceNo(instance_no);
				model.setInterfaceNo("FI-T2-010");
				model.setSapCompanyCode(CommonService.IsNullRNull(table.getString("SAP_COMPANY_CODE")));
				model.setSapPlantCode(CommonService.IsNullRNull(table.getString("SAP_PLANT_CODE")));				
				
				//Request
				model.setDocumentDate(CommonService.IsNullRNull(table.getString("DOC_DATE")));								
				model.setDocumentRequestNo(CommonService.IsNullRNull(table.getString("REQUEST_NO")));
				model.setRequestType("PB");
				model.setRequestNo(null);
				model.setRequestSeries(null);
				
				//add 2012-10-01 dr.tree running record
				model.setSeqNo(i+1);
				
				model.setBuildingPhase(CommonService.IsNullRNull(table.getString("BUILDING_PHASE")));
				model.setZoneCode(CommonService.IsNullRNull(table.getString("ZONE_CODE")));
				model.setUnitNumber(CommonService.IsNullRNull(table.getString("UNIT_NUMBER")));
				
				//Contract								
				model.setContractRefType(null);
				model.setContractRefSeries(null);
				model.setContractRefNo(null);
				model.setRefDocContractNo(CommonService.IsNullRNull(table.getString("REF_NO")));
				
				//model.setInstallmentNumber(CommonService.IsNullRNull(table.getString("INSTALLMENT_NUMBER")));
				
				//Add 2013-03-15
				//DR.TREE
				//Support PO Multi line 
				model.setInstallmentNumberSrt(CommonService.IsNullRNull(table.getString("INSTALLMENT_NUMBER")));
				try{
					//Comment 
					//Add 2013-03-15
					//DR.TREE
					//Position : 0 is Installment number (Low rise)
					//Position : 1 is Seq of contract unit line (Low rise)
					String [] temp = CommonService.IsNullRString(model.getInstallmentNumberSrt()).split("\\-");
					if(temp != null){
						if(temp.length == 1){
							String val = CommonService.IsNullRString(temp[0]);
							if(!val.toUpperCase().equals("NULL") && !CommonService.IsNull(val))
								model.setInstallmentNumber(val);
						}
						
						if(temp.length == 2){
							String val = CommonService.IsNullRString(temp[0]);
							if(!val.toUpperCase().equals("NULL") && !CommonService.IsNull(val))
								model.setInstallmentNumber(val);
							
							val = CommonService.IsNullRString(temp[1]);
							if(!val.toUpperCase().equals("NULL") && !CommonService.IsNull(val))
								model.setContUnitSeq(val);
						}	
					}
				}catch(Exception e){
					e.printStackTrace();
					log.error(e.getMessage());
				}
				
				model.setChequeDate(CommonService.IsNullRNull(table.getString("CHEQUE_DATE")));
				model.setPaymentAmount(CommonService.IsNullRZero(table.getString("PAYMENT_AMOUNT")));
				
				//Set Txn Reacord
				model.setCreatedOn(CommonService.IsNullRNull(table.getString("CREATED_ON")));
				model.setCreatedBy(CommonService.IsNullRNull(table.getString("CREATED_BY")));
				model.setUpdatedOn(CommonService.IsNullRNull(table.getString("LAST_UPD_ON")));
				model.setUpdatedBy(CommonService.IsNullRNull(table.getString("LAST_UPD_BY")));
				
				if(CommonService.IsNull(table.getString("LAST_UPD_ON")))
					model.setActionHandler(ACTION_HANDLER.INSERTED.toString());
				else 
					model.setActionHandler(ACTION_HANDLER.UPDATED.toString());
				
				if(CommonService.IsNull(model.getUpdatedBy()))
					model.setUpdatedBy(model.getCreatedBy());
				
				if(CommonService.IsNull(model.getUpdatedOn()))
					model.setUpdatedOn(model.getCreatedOn());
				
				//Set SAP External Key link
				model.setExtRefKey(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_KEY")));
				model.setExtRefNo(CommonService.IsNullRNull(table.getString("SYNC_EXTERNAL_REF_NO")));				
				model.setStatus(CommonService.IsNullRNull(table.getString("STATUS")));				
				model.setInterfaceNo("FI-T2-010");
				
				//Add DR.TREE
				//DATE : 2013-04-05
				//TABLE : PAYMENT_REQUEST_INSTALLMENT field : (seq, installment_seq)
				model.setLineInstKey(CommonService.IsNullRNull(table.getString("SEQUENCE")));
				
				lst_object.add(model);
			}
			
			//Insert to Staging 
			FiLivOutgoingpaymentInbServ.Inserted(lst_object);
			
			//find by instanceNo
			lst = FiLivOutgoingpaymentInbServ.findByInstanceNo1(instance_no);
			if(!CommonService.IsNull(lst))
			{				
				PaymentRequestOutgoingAction execcc = new PaymentRequestOutgoingAction();
				boolean isvalidate = execcc.CheckedValidattion(lst);
				
				if(isvalidate){					
					//find by instance
					lst = FiLivOutgoingpaymentInbServ.findByInstanceNo1(instance_no);
					
					if(CommonService.getSize(lst) > 0){
						String status = CommonService.IsNullRString(lst.get(0).getStatus());
						if(status.equals("A")){
							//CREATE TO PROMIS
							execcc.CreatedToPromis(lst);
						}else if(status.equals("Z")){
							//CALCEN TO PROMIS
							execcc.CanceledRequestForPayment(lst);
						}
					}
					if(CommonService.getSize(lst) == records){
						for(int i = 0; i < records; i++)
						{
							FiLivOutgoingpaymentInb obj = lst.get(i);
							table.setRow(i);
							table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
							table.setValue("S", "MSG_CODE");
							table.setValue("Success", "MSG_DESC");
							table.setValue("SAP NO =" + obj.getExtRefNo(), "MSG_ALT_DESC");
							table.setValue("", "MSG_ACTION_RESULT");	
							CommonJCOReturn.toString(table);
						}
					}else
						throw new Exception("List size not eq record FiLivOutgoingpaymentInb instance_no=" + instance_no);
				}else
				{
					//have error
					if(CommonService.getSize(lst) == records){
						for(int i = 0; i < records; i++)
						{
							FiLivOutgoingpaymentInb obj = lst.get(i);
							table.setRow(i);
							table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
							table.setValue(obj.getMsgCode(), "MSG_CODE");
							table.setValue(obj.getMsgDesc(), "MSG_DESC");
							table.setValue("SAP NO =" + obj.getExtRefNo(), "MSG_ALT_DESC");
							table.setValue("", "MSG_ACTION_RESULT");	
							CommonJCOReturn.toString(table);
						}
					}else
						throw new Exception("List size not eq record FiLivOutgoingpaymentInb instance_no=" + instance_no);
				}				
			}else
				System.out.println("find not found  instance no = " + instance_no);
		}
		catch(Exception e)
		{	log.error(e.getMessage());
			if(CommonService.getSize(lst) == records){
				for(int i = 0; i < records; i++)
				{
					FiLivOutgoingpaymentInb obj = lst.get(i);
					table.setRow(i);
					table.setValue(CommonService.IsNullRString(obj.getPromisStagingId()), "PROMIS_TXN_ID");
					table.setValue("E", "MSG_CODE");
					table.setValue(e.getMessage(), "MSG_DESC");
					table.setValue("SAP NO =" + obj.getExtRefNo(), "MSG_ALT_DESC");
					table.setValue("", "MSG_ACTION_RESULT");
					
					try {
						log.info(CommonJCOReturn.toString(table));
					} catch (Exception e1) {
						log.error(e.getMessage());
						System.err.println(e.getMessage());
					}
				}
			}else
			{
				for(int i = 0; i < records; i++)
				{
					table.setRow(i);
					table.setValue("E", "MSG_CODE");
					table.setValue("List size not eq record FiLivOutgoingpaymentInb", "MSG_DESC");
				}
			}			
		}
	}
}